<template>
  <!-- 工作中心表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="700"
    draggable
    @close="closeDialog"
    :destroy-on-close="true"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="110px">
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="工作中心编号"
            prop="workshopCode"
            style="width: 310px"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.workshopCode"
              placeholder="请输入工作中心编号"
              clearable
            />
            <el-text v-else>{{ formData.workshopCode }}</el-text>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作中心名称" prop="workshopName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.workshopName"
              placeholder="请输入工作中心名称"
              clearable
            />
            <el-text v-else>{{ formData.workshopName }}</el-text>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="成本中心编号"
            prop="costCenterCode"
            style="width: 310px"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.costCenterCode"
              placeholder="请输入成本中心编号"
              clearable
            />
            <el-text v-else>{{ formData.costCenterCode }}</el-text>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大产能负荷" prop="maxCapacityLoad">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.maxCapacityLoad"
              placeholder="请输入最大产能负荷"
              clearable
            >
              <template #append>%</template>
            </el-input>
            <el-text v-else>{{ formData.maxCapacityLoad }}%</el-text>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="外部编号"
            prop="externalCode"
            style="width: 310px"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.externalCode"
              placeholder="请输入外部编码"
              clearable
            />
            <el-text v-else>{{ formData.externalCode }}</el-text>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="位置描述"
            prop="positionDescription"
            style="width: 330px"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.positionDescription"
              placeholder="请输入位置描述"
              clearable
            />
            <el-text v-else>{{ formData.positionDescription }}</el-text>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工厂" prop="plantId" style="width: 310px">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.plantId"
              placeholder="请选择工厂"
              clearable
              style="width: 330px"
              @change="plantChange"
              filterable
            >
              <el-option
                v-for="item in plants"
                :key="item.id"
                :label="item.organizationCode"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.plantCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作日历类型" prop="workCalendarTypeId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.workCalendarTypeId"
              placeholder="请输入工作日历类型"
              clearable
              style="width: 330px"
              filterable
            >
              <el-option
                v-for="item in workCalendarTypes"
                :key="item.id"
                :label="item.workCalendarTypeName"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.workCalendarTypeName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="启用状态" prop="enabled">
            <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
            <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="虚拟工作中心" prop="isVirtual">
            <el-radio-group
              v-model="formData.isVirtual"
              v-if="!props.isReadonly"
            >
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
            <span v-else>{{ useDictionary("YesNo", formData.isVirtual) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="工作中心分组"
            prop="groupType"
            style="width: 310px"
          >
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.groupType"
              placeholder="请选择工作中心分组"
              clearable
              style="width: 330px"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList(
                  'WorkCenterGroup'
                )"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              useDictionary("WorkCenterGroup", formData.groupType)
            }}</span>
          </el-form-item>
        </el-col>
        <el-form-item label="备注" prop="remarks" style="width: 670px">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.remarks"
            placeholder="请输入备注"
            type="textarea"
            :rows="2"
            clearable
          />
          <el-text v-else>{{ formData.remarks }}</el-text>
        </el-form-item>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="创建时间"
            prop="createTime"
            v-if="props.isReadonly"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.createTime"
              disabled
            />

            <span v-else>{{ formData.createTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="创建人"
            prop="createdUserName"
            v-if="props.isReadonly"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.createdUserName"
              disabled
            />

            <span v-else>{{ formData.createdUserName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="更新时间"
            prop="lastUpdateTime"
            v-if="props.isReadonly"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lastUpdateTime"
              disabled
            />

            <span v-else>{{ formData.lastUpdateTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="更新人"
            prop="lastUpdatedUserName"
            v-if="props.isReadonly"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lastUpdatedUserName"
              disabled
            />

            <span v-else>{{ formData.lastUpdatedUserName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESWORKSHOPADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    //点击编辑或查看时获取组件传值中工厂编号，并查询工作日历类型
    getWorkCalendarType(JSON.parse(JSON.stringify(props.data)).plantId);
  }
);

const rules = reactive({
  workshopCode: [
    { required: true, message: "请输入工作中心编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  workshopName: [
    { required: true, message: "请输入工作中心名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  isVirtual: [
    { required: true, message: "请输选择虚拟工作中心", trigger: "change" },
  ],
  costCenterCode: [
    { required: true, message: "请输入成本中心编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  positionDescription: [
    { required: true, message: "请输入位置描述", trigger: "blur" },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  maxCapacityLoad: [
    {
      required: true,
      message: "请输入最大产能负荷",
      trigger: "blur",
    },
    {
      required: true,
      pattern: /^\d{1,18}(\.\d{0,6})?$/,
      message: "十八位整数,六位小数",
      trigger: "blur",
    },
  ],
  workCalendarTypeId: [
    { required: true, message: "请输入工作日历类型", trigger: "change" },
  ],
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  groupType: [
    { required: true, message: "请选择工作中心分组", trigger: "change" },
  ],
  externalCode: [
    { required: true, message: "外部编号", trigger: "change" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [{ required: true, trigger: "change" }],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  workshopCode: "",
  workshopName: "",
  isVirtual: 1,
  costCenterCode: "",
  positionDescription: "",
  maxCapacityLoad: "",
  workCalendarTypeId: "",
  workCalendarTypeName: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  groupType: "",
  externalCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        workshopCode,
        workshopName,
        isVirtual,
        costCenterCode,
        positionDescription,
        maxCapacityLoad,
        workCalendarTypeId,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        groupType,
        externalCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        workshopCode,
        workshopName,
        isVirtual,
        costCenterCode,
        positionDescription,
        maxCapacityLoad,
        workCalendarTypeId,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        groupType,
        externalCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
      //编辑时回显字典label
      formData.groupType = String(formData.groupType);
    }
  }
);
//工厂信息
const plants: any = ref([]);
//工作日历类型
const workCalendarTypes: any = ref([]);
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.workshopCode = "";
  formData.workshopName = "";
  formData.isVirtual = 1;
  formData.costCenterCode = "";
  formData.positionDescription = "";
  formData.maxCapacityLoad = "";
  formData.workCalendarTypeId = "";
  formData.workCalendarTypeName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.groupType = "";
  formData.externalCode = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  workCalendarTypes.value = [];
}

const loading = ref(false);

/** 工作中心保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mesworkshop/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
onMounted(() => {
  getPlants();
});
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
//查询工厂
async function getPlants() {
  await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  }).then((res) => {
    plants.value = res.data;
  });
}
//工厂信息变更选择工作日历类型
function plantChange() {
  //工厂变更时清楚工作日历类型
  workCalendarTypes.value = [];
  formData.workCalendarTypeId = "";
  getWorkCalendarType(formData.plantId);
  plants.value.forEach((item: any) => {
    if (item.id == formData.plantId) {
      formData.plantCode = item.organizationCode;
    }
  });
}
//根据工厂code查询工作日历类型
async function getWorkCalendarType(id: String) {
  if (id) {
    await request({
      url: "mdm/mdmworkcalendartype/getList",
      method: "post",
      data: { plantId: id },
    }).then((res) => {
      workCalendarTypes.value = res.data;
      //formData中类型id存在时获取类型名称赋值给formData中的类型名称，查询显示类型名称
      if (formData.workCalendarTypeId) {
        workCalendarTypes.value.forEach((item: any) => {
          if (item.id == formData.workCalendarTypeId) {
            formData.workCalendarTypeName = item.workCalendarTypeName;
          }
        });
      }
    });
  }
}
</script>
